package cn.edu.xmu.tangzk.scala.byexs

import scala.util.Random

/**
 * 实现迭代下降优化算法
 */
object Ex04_4_1 {

    /**
     * guess 猜测值
     * x 实际值
     */
    def sqrtIter(guess: Double, x: Double): Double = {
        println(guess)
        if (isGoodEnough(guess, x)) guess
        else {
            sqrtIter(improve(guess, x), x)
        }
    }

    def improve(guess: Double, x: Double): Double = {
        (guess + x / guess) / 2
    }

    def isGoodEnough(guess: Double, x: Double) = {
        abs(square(guess) - x) <= math.ulp(x)
    }

    def abs(x: Double) = { if (x > 0) x else -x }

    def square(x: Double) = { x * x }

    def main(args: Array[String]) {
        val x = sqrtIter(1, 4)
        assert(x == 2)
    }

}